import React, { useState } from 'react';
import axios from 'axios';
import { message, Progress } from 'antd';
import uuid from 'react-uuid';
import './UniversalPage.css';
import { serverUrl } from "../../config/config.tsx";

interface PageProps {
    title: string;
    type: string;
    estimateWaitTime: number;
}

const Page: React.FC<PageProps> = ({ title, type, estimateWaitTime }) => {
    const [selectedImage, setSelectedImage] = useState<File | null>(null);
    const [resultImage, setResultImage] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [progress, setProgress] = useState<number>(0);
    const [statusMessage, setStatusMessage] = useState<string>('');

    const MAX_FILE_SIZE_MB = 5;
    const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024;

    const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0] ?? null;
        if (file) {
            if (file.size > MAX_FILE_SIZE_BYTES) {
                message.error(`图片太大，请选择小于 ${MAX_FILE_SIZE_MB} MB 的图片`);
                setSelectedImage(null);
            } else {
                setSelectedImage(file);
                setResultImage(null);
            }
        }
    };

    const handleSubmit = async () => {
        if (!selectedImage) return;

        setIsLoading(true);
        setProgress(0); // Reset progress
        const taskId = uuid();

        try {
            message.info("任务开始，请稍候...");

            const formData = new FormData();
            formData.append('taskId', taskId);
            formData.append('type', type);
            formData.append('file', selectedImage);

            await axios.post(serverUrl + '/comfy/prompt', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            const startTime = Date.now();

            const pollProgress = () => {
                axios.get(serverUrl + `/comfy/progress?taskId=${taskId}`).then(response => {
                    console.log('Progress:', response.data);

                    if (response.data.data.status === '完成') {
                        setProgress(100);
                        clearInterval(pollInterval);
                        setResultImage(response.data.data.outputPath);
                        message.success("任务成功！");
                        setIsLoading(false);
                    } else if (response.data.data.status === '错误' || response.data.data.status === '任务下发失败'
                        || response.data.data.status === '任务执行错误') {
                        clearInterval(pollInterval);
                        setProgress(0);
                        message.error("任务过程出错！");
                        setIsLoading(false);
                    } else if (response.data.data.status === '排队中') {
                        setStatusMessage('正在排队中...');
                        setProgress(0);
                    } else if (response.data.data.status === '进行中') {
                        const elapsedTime = (Date.now() - startTime) / 1000;
                        if (elapsedTime < estimateWaitTime) {
                            const newProgress = Math.min(99, Math.floor((elapsedTime / estimateWaitTime) * 99)); // 取整数
                            setProgress(newProgress);
                        }
                        setStatusMessage('进行中...');
                    }
                }).catch(error => {
                    console.error('Error:', error);
                    message.error("轮询时出错！");
                    setIsLoading(false);
                    clearInterval(pollInterval);
                });
            };

            const pollInterval = setInterval(pollProgress, 3000);

        } catch (error) {
            console.error('Error:', error);
            message.error("任务过程出错！");
            setIsLoading(false);
        }
    };


    return (
        <div className="universal-page">
            <div className="universal-content">
                <h1 className="universal-title">
                    {title}
                </h1>
                <div className="universal-upload-area">
                    <label htmlFor="file-upload" className="universal-custom-file-upload">
                        {selectedImage ? '更换图片' : '选择图片'}
                    </label>
                    <input id="file-upload" type="file" accept="image/*" onChange={handleImageChange} />
                    {selectedImage && (
                        <button className="universal-submit-button" onClick={handleSubmit} disabled={isLoading}>
                            {isLoading ? '处理中...' : '开始重绘'}
                        </button>
                    )}
                </div>
                {selectedImage && (
                    <div className="universal-image-display">
                        <div className="universal-image-container">
                            <img src={URL.createObjectURL(selectedImage)} alt="Selected" className="universal-preview-image" />
                            <div className="universal-image-label universal-image-label-original">原图</div>
                        </div>
                        <div className="universal-image-container">
                            {isLoading ? (
                                <div className="universal-loading-container" style={{ minWidth: '200px' }}>
                                    <Progress type="circle" percent={progress} />
                                    <p>{statusMessage}</p>
                                </div>
                            ) : (
                                resultImage ? (
                                    <img src={resultImage} alt="Result" className="universal-result-image" />
                                ) : (
                                    <div className="universal-placeholder">
                                        <p>点击上方重绘按钮以开始</p>
                                    </div>
                                )
                            )}
                            <div className="universal-image-label universal-image-label-new">重绘</div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default Page;
